<template>
  <div>
    <BasicTable @register="registerTable">
      <!--插槽:table标题按钮-->
      <template #tableTitle>
        <a-button type="primary" preIcon="ant-design:plus-outlined" @click="handleAdd" v-if="!startEdit" :disabled="btnIsDisabled">新增</a-button>
        <a-button type="primary" @click="handleEdit" v-if="!startEdit && !startAdd" :disabled="btnIsDisabled">批量编辑</a-button>
        <a-button type="primary" preIcon="ant-design:export-outlined" @click="onExportXls">导出</a-button>
        <j-upload-button type="primary" preIcon="ant-design:import-outlined" @click="onImportXls" :disabled="btnIsDisabled">导入</j-upload-button>
        <a-button type="primary" @click="handleSave" v-if="startEdit || startAdd">保存</a-button>
        <a-button @click="handleCancel" v-if="startEdit || startAdd">取消</a-button>
      </template>
      <!--插槽:table标题-->
      <template #headerCell="{ column }">
        <template v-if="column.dataIndex && column.required">{{ column.customTitle }}<span style="color: red">*</span> </template>
        <span v-else> {{ column.customTitle }}</span>
      </template>
      <template #bodyCell="{ column, text, record }">
        <template v-if="column.editRow && column.editComponent === 'Input'">
          <a-input v-if="startEdit || record.isAdd" v-model:value="record[column['dataIndex']]" />
          <span v-else>
            {{ text }}
          </span>
        </template>
        <template v-if="column.editRow && column.editComponent === 'InputNumber'">
          <a-input-number v-if="startEdit || record.isAdd" v-model:value="record[column['dataIndex']]" />
          <span v-else>
            {{ text }}
          </span>
        </template>
        <template v-if="column.editRow && column.editComponent === 'Select'">
          <a-select v-if="startEdit || record.isAdd" v-model:value="record[column['dataIndex']]" :options="personList" :fieldNames="{ label: 'psnName', value: 'psnNum' }" style="width: 100%" @change="(e, option) => personListChange(e, option, record)" />
          <span v-else>
            {{ text }}
          </span>
        </template>
      </template>
      <!--操作栏-->
      <template #action="{ record, index }">
        <TableAction :actions="getTableAction(record, index)" />
      </template>
    </BasicTable>
  </div>
</template>

<script lang="ts" name="emp-team-checkIn3-HubTeamResultKeyTask" setup>
import { ref, onMounted, reactive, nextTick, watchEffect, computed, unref, watch, defineComponent } from 'vue';
import { BasicTable, TableAction } from '/@/components/Table';
import { useListPage } from '/@/hooks/system/useListPage';
import { columns, searchFormSchema } from './HubTeamResultKeyTask.data';
import { list, deleteOne, getImportUrl, getExportUrl, updateList } from './HubTeamResultKeyTask.api';
import { getPeriodTree, getBaseRelList, getMonitoringStatus } from '/@/api/common/api';
import { useMessage } from '/@/hooks/web/useMessage';
import dayjs from 'dayjs';
import { useUserStore } from '/@/store/modules/user';
const userStore = useUserStore();

const btnIsDisabled = ref(false);
const { createMessage: $message } = useMessage();
//注册table数据
const { prefixCls, tableContext, onExportXls, onImportXls, } = useListPage({
  tableProps: {
    title: 'hub_team_result_key_task',
    api: list,
    columns,
    canResize: false,
    // dataSource: mockDate,
    showIndexColumn: true,
    beforeFetch: (params) => {
      startEdit.value = false;
      return Object.assign(params);
    }, //表格和查询条件同步更新的方法
    formConfig: {
      //labelWidth: 120,
      schemas: searchFormSchema,
      autoSubmitOnEnter: true,
      showAdvancedButton: true,
      fieldMapToNumber: [],
      fieldMapToTime: [],
    },
    actionColumn: {
      width: 120,
      fixed: 'right',
    },
    immediate: true,
  },
  exportConfig: {
    name: '重点工作积分',
    url: getExportUrl,
  },
  importConfig: {
    url: getImportUrl,
    success: handleSuccess,
  },
});

const [registerTable, { getForm, reload, getDataSource, setTableData }, { rowSelection, selectedRowKeys }] = tableContext;

// 人员下拉框列表
const personList: any = ref([]);

// 默认执行一次
const orgName = ref(userStore.getOrgName);
onMounted(async () => {
  let form = getForm();
  //获取编辑按钮的状态
  await getBtnStatus();
  personList.value = await getBaseRelList({ orgCode: userStore.getOrgCode })
  form.updateSchema([
    {
      field: 'periodCode',
      label: '考核周期',
      component: 'ApiTreeSelect',
      componentProps: {
        api: getPeriodTree,
        fieldNames: {
          children: 'child',
          label: 'periodName',
          value: 'periodCode',
        },
        onChange: (e) => {
          handleSuccess();
        },
      },
    },
    {
      field: 'orgCode',
      componentProps: {
        onChange: (e, i) => {
          orgName.value = i?.label;
          handleSuccess();
        },
        // atfer request callback
        onOptionsChange: (options) => {
          console.log('get options', options.length, options);
        },
      },
    },
  ]);
});

const startEdit = ref(false);
const startAdd = ref(false);
let backData = [];
// console.log('222', getDataSource());
const handleEdit = () => {
  backData = JSON.parse(JSON.stringify(getDataSource()));
  startEdit.value = true;
  startAdd.value = false;
};

const handleAdd = () => {
  let formData = getForm().getFieldsValue();
  if (!formData.periodCode) {
    $message.warn('请选择考核周期');
    return;
  }
  backData = JSON.parse(JSON.stringify(getDataSource()));
  startEdit.value = false;
  startAdd.value = true;
  let dataSource = getDataSource();
  dataSource.unshift({
    isAdd: true,
  });
  setTableData(dataSource);
};

const handleCancel = () => {
  startEdit.value = false;
  startAdd.value = false;
  reload();
  // setTableData(backData);
};

const handleSave = () => {
  let dataSource = getDataSource();
  let flagMsg: any = null;
  dataSource.forEach((item) => {
    if (!item.psnName) {
      flagMsg = '姓名不能为空';
    } else if (!item.keyContent) {
      flagMsg = '重点工作内容不能为空';
    } else if (!item.finalScore) {
      flagMsg = '评分不能为空';
      return;
    }
  });
  if (flagMsg) {
    $message.warn(flagMsg);
    return;
  }
  const saveData = {
    datas: dataSource,
    orgCode: getForm().getFieldsValue().orgCode,
  };
  updateList(saveData).then((res) => {
    startEdit.value = false;
    startAdd.value = false;
    reload();
  });
};

const personListChange = (e, option, record) => {
  // let dataSource = getDataSource();
  let formData = getForm().getFieldsValue();
  if (!formData.periodCode) {
    record.psnName = null;
    return $message.warn('请选择考核周期');
  }
  // dataSource.forEach((item) => {
  // if (item.id == record.id) {
  // console.log('11```', option);
  // item.value = { ...item, ...option };
  record.psnName = option.psnName;
  record.psnNum = option.psnNum;
  record.personType = option.personType;
  record.periodCode = formData.periodCode;
  record.orgCode = option.orgCode;
  record.orgName = option.orgName;
  // }
  // });
  // console.log('111', dataSource);
  // setTableData(dataSource);
};
/**
 * 删除事件
 */
async function handleDelete(record, index) {
  let tableData = getDataSource();
  if (!record.id) {
    tableData.splice(index, 1);
    setTableData(tableData);
  } else {
    await deleteOne({ id: record.id }, handleSuccess);
  }
  // await deleteOne({ id: record.id }, handleSuccess);
}
/**
 * 成功回调
 */
async function handleSuccess() {
  //查看按钮组操作状态
  await getBtnStatus();
  //重置编辑状态
  startEdit.value = false;
  (selectedRowKeys.value = []) && reload();
}
/**
 * 操作栏
 */
function getTableAction(record, index) {
  return [
    {
      label: '删除',
      popConfirm: {
        title: '是否确认删除',
        confirm: handleDelete.bind(null, record, index),
      },
      disabled: btnIsDisabled.value,
    },
  ];
}

const getBtnStatus = () => {
  getMonitoringStatus({
    orgCode: getForm().getFieldsValue().orgCode,
    periodCode: getForm().getFieldsValue().periodCode,
  }).then((res) => {
    btnIsDisabled.value = res.data == '2';
  });
};
</script>

<style scoped lang="less">
/deep/.ant-table-wrapper {
  padding: 16px !important;
}
</style>
